<?php

// +--------------------------------------------------------
// | Name： 四川大朵 产品接口api
// +--------------------------------------------------------
// | Version： V5.0
// +--------------------------------------------------------
// | Author: xkyinzhe <zhonghuaxinxing@sina.cn>
// +--------------------------------------------------------
// | Time: 2021-05-06 13:04
// +--------------------------------------------------------
declare(strict_types=1);

namespace app\api\controller\v1;

use app\common\common\IndexController;
use app\common\model\Collect as CollectModel;
use app\common\model\GoodsCommon as GoodsCommonModel;
use app\common\model\Goods as GoodsModel;
use app\common\model\GoodsCate as GoodsCateModel;
use app\common\model\GoodsPic as GoodsPicModel;
use app\common\model\HistorySearch as HistorySearchModel;
use app\common\model\SpecPrice as SpecPriceModel;
use app\common\model\GoodsSpecValue as GoodsSpecValueModel;
use app\common\model\User as UserModel;
use app\common\model\Coupon as CouponModel;
use app\common\model\UserCoupon as UserCouponModel;
use app\common\model\HistoryGoods as HistoryGoodsModel;
use app\common\model\Artice as ArticeModel;
use think\facade\Db;

/**
 * @xk 产品接口API
 */
class Goods extends IndexController
{
    /**
     * @xk 获取商品列表
     *
     * @method getGoodsList
     *
     * @param GoodsModel $goodsModel [description]
     *
     * @return [type] [description]
     * @Author xkyinzhe                <zhonghuaxinxing@sina.cn>
     * @Time   2021-05-06T13:34:03+080
     */
    public function getGoodsList(UserModel $userModel,GoodsModel $goodsModel, HistorySearchModel $historySearchModel)
    {
        $param = request()->param();
        $keywords = isset($param['keywords']) ? $param['keywords'] : '';
        $page = isset($param['page']) ? (int) $param['page'] : 1; // 当前页
        $limit = isset($param['limit']) ? (int) $param['limit'] : 20; // 请求数量
        $is_page = isset($param['is_page']) ? $param['is_page'] : 1; // 是否进行分页
        $user_sn = isset($param['user_sn']) ? $param['user_sn'] : '';
        $order_act = isset($param['order_act']) ? $param['order_act'] : 'order_id';
        $order_sort = isset($param['order_sort']) ? $param['order_sort'] : 'desc';
        $condition = [];
        $condition[] = ['g.is_onsell','=',1];
        if ('' != $keywords) {
            $condition[] = ['g.goods_name', 'like', '%'.$keywords.'%'];
            if ('' != $user_sn) {
                $historySearchModel->create(['user_sn' => $user_sn, 'keywords' => $keywords]);
            }
        }
        $code = 200;
        $msg = '请求成功';
        $resultData = [];
        try {
            $result_count = $goodsModel->alias('g')->where($condition)->count(); // 请求总数量
            if ($result_count <= ($page - 1) * $limit) {
                $resultData['list'] = [];
                $resultData['page'] = $page;
                throw new \think\Exception("没有更多数据了", 203);
            }
            $order = $order_act." ".$order_sort;
            $list = $goodsModel
                ->alias('g')
                ->where($condition)
                ->field('g.`goods_id`,g.`goods_name`,g.`goods_cate_id`,g.`picurl`,g.`selling_price`,g.`market_price`,g.`shell_num`,g.update_time,g.`keywords`,g.`vip_buy_bili`')
                ->withAttr('picurl', function ($value, $data) {
                    if ($value) {
                        return getShowUrl($value);
                    }
                })
                ->order($order)
                ->page($page, $limit)
                ->select()
                ->toArray();
            // 获取用户信息 判断用户首购/复购
            $is_buy = $userModel->where([['user_sn','=',$user_sn]])->value('`is_buy`');
            if ($list && $is_buy == 1) {
                foreach ($list as $key => $value) {
                    $list[$key]['selling_price'] = sprintf('%.2f',((float)$value['selling_price']*(float)$value['vip_buy_bili'])); // 最终获得折扣价格
                    $list[$key]['is_buy'] = 1;
                }
            }
            $result_code = 200;
            $result_msg = '加载成功';
            $resultData = [];
            $resultData['list'] = $list;
            $resultData['page'] = $page + 1;
        } catch (\Exception $e) {
            $result_code = 200;
            if ($e->getCode() == 203) {
                $result_code = 203;
            }
            $result_msg = $e->getMessage();
        }
        $this->result($code, $msg, $result_code, $result_msg, $resultData, $result_count);
    }

    /**
     * @xk 获取商品详情
     *
     * @method getGoodsShow
     *
     * @param GoodsModel $goodsModel [description]
     *
     * @return [type] [description]
     * @Author xkyinzhe                <zhonghuaxinxing@sina.cn>
     * @Time   2021-05-06T14:28:19+080
     */
    public function getGoodsShow(
        GoodsModel $goodsModel,
        GoodsPicModel $goodsPicModel,
        SpecPriceModel $specPriceModel,
        GoodsSpecValueModel $goodsSpecValueModel,
        ArticeModel $articeModel,
        UserModel $userModel
    ) {
        $code = 200;
        $msg = '请求成功';
        $param = request()->param();
        $resultData = [];
        $user_sn = isset($param['user_sn']) ? $param['user_sn'] : '';
        $goods_id = isset($param['goods_id']) ? $param['goods_id'] : 0;
        $condition = [];
        $condition[] = ['goods_id', '=', $goods_id];
        if ($goods_id <= 0) {
            $result_code = 300;
            $result_msg = '请选择需要操作的产品';
            $resultData['type'] = '_black';
            $this->result($code, $msg, $result_code, $result_msg, $resultData);
        }
        // 开始整合 产品详情相关信息
        $resultData['info'] = $goodsModel
                              ->with(['getGoodsParameters'])
                              ->alias('g')
                              ->field('g.`goods_id`,g.`goods_name`,g.`fileurl`,g.`content`,g.`selling_price`,g.`market_price`,g.`shell_num`,g.`picurl`,g.`postage_des`,g.`keywords`,g.`is_onsell`,g.`stock`,g.`store_id`,g.`achievement_bili`,g.`is_buy`,g.`vip_buy_bili`')
                              ->withAttr('fileurl', function ($value, $data) {
                                  return getShowUrl($value);
                              })
                              ->withAttr('picurl', function ($value, $data) {
                                  return getShowUrl($value);
                              })
                              ->withAttr('content', function ($value, $data) {
                                  return chanageContent($value);
                              })
                              ->withAttr('des', function ($value, $data) {
                                  return chanageContent($value);
                              })
                              ->withAttr('is_buy', function ($value, $data) {
                                  return 0;
                              })
                              ->find($goods_id);
        // 获取产品组图
        $resultData['goods_pic_arr'] = $goodsPicModel
                                      ->where($condition)
                                      ->field('`picurl`,`picname`')
                                      ->withAttr('picurl', function ($value, $data) {
                                          if ($value) {
                                              return getShowUrl($value);
                                          }
                                      })
                                      ->select()
                                      ->toArray();
        // 获取产品规格
        $spec_str = $specPriceModel->where([['goods_id', '=', $goods_id]])->column("GROUP_CONCAT(`sku_key` SEPARATOR '_') AS items_id");
        $attr = [];
        if ($spec_str[0]) {
            $spec_arr = str_replace('_', ',', $spec_str[0]);
            $spec_value_list = $goodsSpecValueModel
                             ->alias('sv')
                             ->leftJoin('goodsSpec s', 's.goods_spec_id = sv.goods_spec_id')
                             ->where([['sv.goods_spec_value_id', 'in', $spec_arr]])
                             ->field('s.`goods_spec_id`,s.`spec_name`,sv.`goods_spec_value_id`,sv.`spec_value`')
                             ->select()
                             ->toArray();
            if ($spec_value_list) {
                foreach ($spec_value_list as $key => $value) {
                    $item_select = false;
                    $attr[$value['spec_name']][] = [
                      'spec_value_id' => $value['goods_spec_value_id'],
                      'spec_id' => $value['goods_spec_id'],
                      'spec_name' => $value['spec_name'],
                      'item_select' => $item_select,
                      'spec_value' => $value['spec_value'],
                    ];
                }
                foreach ($attr as $key => $value) {
                    foreach ($value as $k => $val) {
                        if ($k == 0) {
                            $attr[$key][$k]['item_select'] = true;
                        }
                    }
                }
            }
        }
        $resultData['attr'] = (array)$attr;
        $resultData['attr_count'] = count($attr);
        $resultData['share_linkurl'] = 'https://'.$_SERVER['HTTP_HOST'].'/#/pages/goods_show/goods_show?goods_id='.$goods_id;
        $resultData['info'] = $resultData['info']?$resultData['info']->toArray():[];
        if ($user_sn) {
            $resultData['share_linkurl'] = 'https://'.$_SERVER['HTTP_HOST'].'/#/pages/goods_show/goods_show?goods_id='.$goods_id.'&share_code='.base64_encode($user_sn);
            $is_buy = $userModel->where([['user_sn','=',$user_sn]])->value('`is_buy`');
            if ($is_buy == 1) {
                $resultData['info']['selling_price'] =
                sprintf('%.2f',((float)$resultData['info']['selling_price']*(float)$resultData['info']['vip_buy_bili']));
                $resultData['info']['is_buy'] = 1;
            }
        }
        if($resultData['info']['is_onsell'] != 1){
          $result_code = 300;
          $result_msg = '商品已下架';
          $resultData = [];
          $resultData['type'] = "_black";
          $this->result($code, $msg, $result_code, $result_msg, $resultData);
        }
        $resultData['info']['postage_des'] =chanageContent($articeModel->where([['cate_id', '=', 6]])->value('content'));
        $result_code = 200;
        $result_msg = '加载成功';
        $this->result($code, $msg, $result_code, $result_msg, $resultData);
    }
    /**
     * @xk 获取产品规格
     *
     * @method getGoodsSpec
     * @param  GoodsModel          $goodsModel                [description]
     * @param  SpecPriceModel      $specPriceModel            [description]
     * @param  GoodsSpecValueModel $goodsSpecValueModel       [description]
     * @return [type]              [description]
     * @Time   2021-10-29
     * @City   青岛
     * @Author xkyinzhe            <zhonghuaxinxing@sina.cn>
     */
    public function getGoodsSpec(
        GoodsModel $goodsModel,
        SpecPriceModel $specPriceModel,
        UserModel $userModel,
        GoodsSpecValueModel $goodsSpecValueModel
    ) {
        $code = 200;
        $msg = '请求成功';
        $param = request()->param();
        $resultData = [];
        $goods_id = isset($param['goods_id']) ? $param['goods_id'] : 0;
        $spec_key = isset($param['spec_key']) ? $param['spec_key'] : '';
        $user_sn = isset($param['user_sn']) ? $param['user_sn'] : '';
        $spec_arrx = [];
        if ($spec_key) {
            $spec_arrx = explode('_', $spec_key);
        }
        $condition = [];
        $condition[] = ['goods_id', '=', $goods_id];
        if ($goods_id <= 0) {
            $result_code = 404;
            $result_msg = '请选择需要操作的产品';
            $this->result($code, $msg, $result_code, $result_msg, $resultData);
        }
        // 开始整合 产品详情相关信息
        $resultData['info'] = $goodsModel
                              ->with(['getGoodsParameters'])
                              ->alias('g')
                              ->field('g.`goods_id`,g.`goods_name`,g.`selling_price`,g.`picurl`,g.`stock`,g.`vip_buy_bili`')
                              ->withAttr('picurl', function ($value, $data) {
                                  return getShowUrl($value);
                              })
                              ->find($goods_id);
        $is_buy = $userModel->where([['user_sn','=',$user_sn]])->value('`is_buy`');
        if ($is_buy == 1) {
            $resultData['info']['selling_price'] = $resultData['info']['selling_price']*$resultData['info']['vip_buy_bili'];
        }
        // 获取产品规格
        $spec_str = $specPriceModel->where([['goods_id', '=', $goods_id]])->column("GROUP_CONCAT(`sku_key` SEPARATOR '_') AS items_id");
        $attr = [];
        if ($spec_str[0]) {
            $spec_arr = str_replace('_', ',', $spec_str[0]);
            $spec_value_list = $goodsSpecValueModel
                             ->alias('sv')
                             ->leftJoin('goodsSpec s', 's.goods_spec_id = sv.goods_spec_id')
                             ->where([['sv.goods_spec_value_id', 'in', $spec_arr]])
                             ->field('s.`goods_spec_id`,s.`spec_name`,sv.`goods_spec_value_id`,sv.`spec_value`')
                             ->select()
                             ->toArray();
            if ($spec_value_list) {
                foreach ($spec_value_list as $key => $value) {
                    $item_select = false;

                    $attr[$value['spec_name']][] = [
                      'spec_value_id' => $value['goods_spec_value_id'],
                      'spec_id' => $value['goods_spec_id'],
                      'spec_name' => $value['spec_name'],
                      'item_select' => $item_select,
                      'spec_value' => $value['spec_value'],
                    ];
                }

                foreach ($attr as $key => $value) {
                    foreach ($value as $k => $val) {
                        if (in_array($val['spec_value_id'], $spec_arrx)) {
                            $attr[$key][$k]['item_select'] = true;
                        } elseif ($k == 0) {
                            $attr[$key][$k]['item_select'] = true;
                        }
                    }
                }
            }
        }
        $resultData['attr'] = (array)$attr;
        $resultData['attr_count'] = count($attr);
        $result_code = 200;
        $result_msg = '加载成功';
        $this->result($code, $msg, $result_code, $result_msg, $resultData);
    }
    /**
     * @xk 获取产品规格信息
     *
     * @method getSpecPrice
     *
     * @param GoodsModel     $goodsModel     [description]
     * @param SpecPriceModel $specPriceModel [description]
     * @param SpecValueModel $specValueModel [description]
     *
     * @return [type] [description]
     * @Author xkyinzhe                <zhonghuaxinxing@sina.cn>
     * @Time   2021-05-10T09:25:07+080
     */
    public function getSpecPrice(
        GoodsModel $goodsModel,
        SpecPriceModel $specPriceModel,
        UserModel $userModel,
        goodsSpecValueModel $goodsSpecValueModel
    ) {
        $param = request()->param();
        $attr = isset($param['attr']) ? $param['attr'] : '';
        $goods_id = isset($param['goods_id']) ? $param['goods_id'] : 0;
        $attr_count = isset($param['attr_count']) ? $param['attr_count'] : 0;
        $user_sn = isset($param['user_sn']) ? $param['user_sn'] : '';
        $code = 200;
        $msg = '请求成功';
        $spec_arr = [];
        // 开始获取选中的规格值
        if ($attr) {
            foreach ($attr as $key => $value) {
                foreach ($value as $k => $val) {
                    if ($val['item_select']=='true') {
                        $spec_arr[] = $val['spec_value_id'];
                    }
                }
            }
        }
        if ($attr_count > 0 && $attr_count != count($spec_arr)) {
            $result_code = 200;
            $result_msg = '请选择完整规格';
            $resultData = [];
            $this->result($code, $msg, $result_code, $result_msg, $resultData);
        }
        $spec_price_info = [];
        if($spec_arr){
          sort($spec_arr);
          $spec_key = implode('_', $spec_arr);
          $spec_price_info = $specPriceModel
                          ->alias('sp')
                          ->leftJoin('goods g', 'g.goods_id=sp.goods_id')
                          ->where([['sp.sku_key', '=', $spec_key], ['sp.goods_id', '=', $goods_id]])
                          ->field('sp.`spec_price_id`,sp.`picurl`,sp.`stock`,sp.`selling_price`,sp.`sku_key`,sp.`sku_value`,sp.`weight`,g.`vip_buy_bili`,g.picurl as goods_pic')
                          ->withAttr('picurl', function ($value, $data) {
                              if($value == '/static/common/images/no_pic.png'){
                                return getShowUrl($data['goods_pic']);
                              }else{
                                return getShowUrl($value);
                              }
                          })
                          ->find();
          if ($user_sn) {
              $is_buy = $userModel->where([['user_sn','=',$user_sn]])->value('`is_buy`');
              if ($is_buy == 1) {
                  $spec_price_info['selling_price'] = sprintf('%.2f',((float)$spec_price_info['selling_price']*(float)$spec_price_info['vip_buy_bili']));
              }
          }
        }
        $result_code = 200;
        $result_msg = '加载成功';
        $resultData = $spec_price_info;
        $this->result($code, $msg, $result_code, $result_msg, $resultData);
    }
    /**
     * @xk 商品详情页WEB
     *
     * @method goodsView
     * @param  GoodsModel              $goodsModel               [description]
     * @return [type]                                            [description]
     * @Author xkyinzhe                <zhonghuaxinxing@sina.cn>
     * @Time   2021-05-13T15:40:57+080
     */
    public function goodsView(GoodsModel $goodsModel)
    {
        $param = request()->param();
        $goods_id = isset($param['goods_id']) ? $param['goods_id'] : 0;
        $info = $goodsModel
          ->where([
              ['goods_id', '=', $goods_id],
          ])
          ->field('goods_name,content')
          ->withAttr('content', function ($value, $data) {
              return chanageContent($value);
          })
          ->find();
        if (is_null($info)) {
            return "<div style='text-align: center;padding: 30px 0;'>暂无详情</div>";
        }
        return web_page($info['goods_name'], $info['content']);
    }
}
